<template>
  <div
    :class="animate"
    :style="{
      height: height,
      width: width,
      overflowX: 'hidden',
      overflowY: overflowY
    }"
    :id="chartOption.bindingDiv"
    @mouseenter="visible"
    @mouseleave="invisible"
    ref="text"
  >
    <el-table
      :show-summary="chartOption.isSum"
      :summary-method="getSummaries"
      :data="getData()"
      @row-click="clickRow"
      :row-class-name="tableRowClassName"
      :cell-style="cellStyle"
      :header-cell-style="headerStyle"
      style="width: 100%;overflow:auto"
      ref="tbody"
      :border="
        this.chartOption.border == undefined ? false : this.chartOption.border
      "
    >
      <el-table-column
        v-for="(item, index) in this.chartOption.cols"
        :sortable="chartOption.isSort"
        :key="index"
        :prop="item.field"
        :label="item.title"
        :show-overflow-tooltip="true"
      >
        <!--<a @click="fieldClick(item.field, item.title)" style="color:blue;cursor:pointer" v-if="isBindingChart(item.field)">{{item.title}}</a>-->
        <template slot-scope="scope">
          <a
            @click="fieldClick(item.field, getFieldValue(item.field, scope))"
            :style="linkStyle(item)"
            v-if="isBindingChart(item.field)"
            >{{ getFieldValue(item.field, scope) }}</a
          >
          <a style="cursor:default;" v-else>{{
            getFieldValue(item.field, scope)
          }}</a>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div style="margin-top:15px;width: 100%;" v-if="chartOption.pagination==undefined || chartOption.pagination==true">
      <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="this.chartOption.pageSize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.tableValue.length"
        style="display: flex;flex-wrap:wrap;"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";
import VueEvent from "@/views/tool/datav/VueEvent";
import "../../animate/animate.css";

import { parseQueryString, fIsUrL } from "../../util/urlUtil";
import { bindChart } from "../../util/LinkageChart";
import { chartApiBar, remoteChartApi,chartBIanalysis  } from "@/api/tool/datav/chartApi";
import { tableBIanalysis } from "@/api/tool/datav/chartBI/chartTableBI";
import { getFormsource } from "@/api/tool/datav/formsource";
const animationDuration = 6000;
import { websocketCommand } from "../../util/websocket.js";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object
    },
    drawingList: {
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      timer: "",
      dataOption: JSON.parse(JSON.stringify(this.chartOption)),
      currentPage: 1, // 当前页码
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className,
      selectedRow: undefined,
      overflowY: "hidden",
      tableValue:this.chartOption.staticDataValue,
    };
  },
  watch: {
    width() {},
    height() {},
    chartOption: {
      deep: true,
      handler(newVal) {
        this.setOptions(JSON.parse(JSON.stringify(newVal)));
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    this.chart = null;
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  computed: {
    cellStyle() {
      var self = this;
      return function({ row, column, rowIndex, columnIndex }) {
        let style = {
          height: self.chartOption.tbodyheight + "px",
          backgroundColor: "transparent",
          fontSize: self.chartOption.tbodyfontsize + "px",
          fontFamily: self.chartOption.tbodyfontfamily,
          color: self.chartOption.tbodyfontcolor,
          textAlign: self.chartOption.isLeft,
          verticalAlign: "middle"
        };
        if (
          rowIndex == self.selectedRow &&
          self.chartOption.selectedColor != null
        ) {
          style.backgroundColor = self.chartOption.selectedColor;
        } else if (self.chartOption.tbodybackgroundcolor != null) {
          style.backgroundColor = self.chartOption.tbodybackgroundcolor;
        }
        return style;
      };
    },
    

    headerStyle() {
      return {
        height: this.chartOption.theadheight + "px",
        backgroundColor: this.chartOption.theadbackgroundcolor,
        fontSize: this.chartOption.theadfontsize + "px",
        fontFamily: this.chartOption.theadfontfamily,
        color: this.chartOption.theadfontcolor,
        textAlign: this.chartOption.isLeft,
        verticalAlign: "middle"
      };
    }
  },
  methods: {
    getData(){
      if(this.chartOption.pagination == true || this.chartOption.pagination == undefined){
       return this.tableValue.slice(
          (this.currentPage - 1) * this.chartOption.pageSize,
          this.currentPage * this.chartOption.pageSize
        )
      }else{
        return this.tableValue
      }
       
    },
    getSummaries(param) {
      
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计';
            return;
          }
          if(this.chartOption.sumField != undefined){
            if(this.chartOption.sumField.indexOf(column.property) > -1){
              const values = data.map(item => Number(item[column.property]));
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0);
                // sums[index] += ' 元';
              } else {
                sums[index] = 'N/A';
              }
            }
          }
          
        });
        if(this.chartOption.sumField != undefined){
          let that = this.$el;
          if(that != undefined){
            let current = document.getElementById(this.chartOption.bindingDiv)
                .querySelector(".el-table__footer-wrapper")
                .querySelector(".el-table__footer").getElementsByTagName("div");
            
            if(current!= undefined){
              for (let cell of current) {
                cell.style.fontSize= this.chartOption.tbodyfontsize + "px" 
                cell.style.height= this.chartOption.tbodyheight + "px";
                cell.style.backgroundColor= this.chartOption.tbodybackgroundcolor;
                cell.style.fontSize= this.chartOption.tbodyfontsize + "px";
                cell.style.fontFamily= this.chartOption.tbodyfontfamily;
                cell.style.color= this.chartOption.tbodyfontcolor;
                cell.style.textAlign= this.chartOption.isLeft;
                cell.style.lineHeight= this.chartOption.tbodyheight + "px";
                cell.style.verticalAlign= "middle"
              }
            }
          }
        }
        return sums;
    },
    initChart() {
      //判断是否开启定时器，当是访问url接口时候并且timeout不为0时候开启定时器
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    setOptions: async function(dataOption) {
      // console.log("=>",dataOption)
      //初始化数据
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url") {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;

        dataOption.staticDataValue = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );

      } else if (dataOption.dataSourceType == "database") {
        if (
          dataOption.database.executeSql != undefined &&
          dataOption.database.executeSql != ""
        ) {
          let result = [];
          if(dataOption.database.sqlType != 'custom'){
          
            result = await tableBIanalysis(dataOption.database);
          }else{
            result = await chartBIanalysis(dataOption.database);
          }
          if (result.code == 200) {
            dataOption.staticDataValue = result.data;

          } else {
            alert("操作数据库错误");
          }
        }
      } else if (dataOption.dataSourceType == "form") {
        if (dataOption.formSource != undefined) {
          let response = await getFormsource(dataOption.formSource.id);
          dataOption.staticDataValue = JSON.parse(response.data.formData);

        }
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;

          }
        }
      } 
      this.tableValue = dataOption.staticDataValue;
        //数据处理
       if(dataOption.customData != undefined && dataOption.customData != ""){
          this.$nextTick(() => {

            try {
              dataOption.staticDataValue = (
               //里面为要处理的代码块 
              eval(dataOption.customData) 
            
              )(
                dataOption.staticDataValue,
                this.$refs.text
              );
              this.tableValue = dataOption.staticDataValue;
            } catch (error) {
              console.log(error)
            }
              
          })
       }

       //交互组件配置
       if(dataOption.interactData != undefined && dataOption.interactData != ""){
          this.$nextTick(() => {

            try {
              dataOption.staticDataValue = (
               //里面为要处理的代码块 
              eval(dataOption.interactData) 
            
              )(
                dataOption.staticDataValue,
                this.$refs.text
              );
              this.tableValue = dataOption.staticDataValue;
            } catch (error) {
              console.log(error)
            }
              
          })
       }
      

      this.getData();
      //设置边框
      if(dataOption.tdBorder == false){
        let rows =  document.getElementById(this.chartOption.bindingDiv)
                  .querySelectorAll(".el-table__row")
        
        for (let row of rows) {
         let tds =  row.getElementsByTagName("td")
          for (let td of tds) {
            td.style.borderBottom = "none"
          }
        }
      }else{
        let rows =  document.getElementById(this.chartOption.bindingDiv)
                  .querySelectorAll(".el-table__row")
        
        for (let row of rows) {
         let tds =  row.getElementsByTagName("td")
          for (let td of tds) {
            td.style.borderBottom = "1px solid #dfe6ec"
          }
        }
      }

    },
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.currentPage = 1;
      this.chartOption.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    rowClick(val) {
      console.log(val);
    },
    getFieldValue(field, scope) {
      // console.log(field);
      // console.log(scope);
      // console.log(scope.row[''+ field +'']);
      return scope.row["" + field + ""];
    },
    fieldClick(field, val) {
      //获取联动图表
      if (this.chartOption.isLink == true) {
        let linkageTag = this.chartOption.linkageCols.filter(function(item) {
          return item.field == field;
        })[0];
        if (linkageTag != undefined) {
          let bindList = linkageTag.bindingChart;

          if (bindList.length > 0) {
            bindChart(linkageTag.paramName, val, bindList, this.drawingList);
          }
        }
      }
      //开启图表下钻
      else if (this.chartOption.isDrillDown == true) {
        //获取联动图表
        let drillTag = this.chartOption.drillCols.filter(function(item) {
          return item.field == field;
        })[0];
        if (drillTag != undefined && drillTag.bindingChart != "") {
          let num = 0;
          for (let i = 0; i < this.chartOption.drillCols.length; i++) {
            if (this.chartOption.drillCols[i].field == drillTag.field) {
              num = i;
            }
          }

          //获取绑定的图表
          let drillDownChartOption = drillTag.drillDownChartOption;

          drillDownChartOption.drillBgColor = drillTag.drillBgColor;

          if (
            drillDownChartOption != undefined &&
            drillDownChartOption != null
          ) {
            //判断是否有参数传递
            if (
              drillTag.paramName != null &&
              drillTag.paramName != "" &&
              drillTag.paramName != undefined
            ) {
              this.$set(
                this.chartOption.drillCols[num].drillDownChartOption
                  .chartOption,
                "requestParameters",
                drillTag.paramName + "=" + val
              );
              drillDownChartOption.chartOption.requestParameters =
                drillTag.paramName + "=" + val;
            } else {
              this.$set(
                this.chartOption.drillCols[num].drillDownChartOption
                  .chartOption,
                "requestParameters",
                ""
              );
              drillDownChartOption.chartOption.requestParameters = "";
            }
            //发送下钻消息
            VueEvent.$emit("drill_down_msg", drillDownChartOption);
          }
        }
      }
      //开启图表远程控制
      if (
        this.chartOption.isRemote == true &&
        this.chartOption.remoteCols.length > 0
      ) {
        //获取联动图表
        let remoteTag = this.chartOption.remoteCols.filter(function(item) {
          return item.field == field;
        })[0];

        if (
          remoteTag != undefined &&
          remoteTag.interfaceKey != undefined &&
          remoteTag.interfaceKey != ""
        ) {
          let remoteData = {};
          //创建ws接口地址数组
          let interfaceArr = new Array();
          let interfaceObj = {
            interfaceKey: remoteTag.interfaceKey,
            interfaceName: remoteTag.interfaceName,
            interfaceUrl: remoteTag.interfaceUrl
          };
          interfaceArr.push(interfaceObj);
          //ws接口参数
          remoteData.interface = interfaceArr;

          let queryObj = {};
          queryObj[remoteTag.field] = val;
          remoteData.query = queryObj;

          // //调用接口
          remoteChartApi(remoteData);
        }
      }
    },
    isBindingChart(field) {
      let remoteTag = false;
      let linkTag = false;

      if (
        this.chartOption.isRemote == true &&
        this.chartOption.remoteCols != undefined
      ) {
        let remoteLinkTag = this.chartOption.remoteCols.filter(function(item) {
          return item.field == field;
        })[0];
        if (remoteLinkTag != null) {
          remoteTag = true;
        }
      }

      if (
        this.chartOption.isLink == true &&
        this.chartOption.linkageCols != undefined
      ) {
        let linkageTag = this.chartOption.linkageCols.filter(function(item) {
          return item.field == field;
        })[0];
        if (linkageTag != null) {
          linkTag = true;
        }
      } else if (
        this.chartOption.isDrillDown == true &&
        this.chartOption.drillCols != undefined
      ) {
        let drillTag = this.chartOption.drillCols.filter(function(item) {
          return item.field == field;
        })[0];
        if (drillTag != null) {
          linkTag = true;
        }
      }

      //远程控制标志以及联动标志同时为false则为false，否则为true
      if (remoteTag == false && linkTag == false) {
        return false;
      } else {
        return true;
      }
    },
    linkStyle(colItem) {
      if (this.chartOption.isLink == true) {
        //获取联动图表
        let linkageTag = this.chartOption.linkageCols.filter(function(item) {
          return item.field == colItem.field;
        })[0];

        if (linkageTag != undefined) {
          return { color: linkageTag.linkColor, cursor: "pointer" };
        }
      } else if (this.chartOption.isDrillDown == true) {
        //获取下钻图表
        let drillTag = this.chartOption.drillCols.filter(function(item) {
          return item.field == colItem.field;
        })[0];

        if (drillTag != undefined) {
          return { color: drillTag.linkColor, cursor: "pointer" };
        }
      }

      if (this.chartOption.isRemote == true) {
        //获取远程控制图表
        let remoteTag = this.chartOption.remoteCols.filter(function(item) {
          return item.field == colItem.field;
        })[0];

        if (remoteTag != undefined) {
          return { color: remoteTag.linkColor, cursor: "pointer" };
        }
      }
    },
    visible() {
      this.overflowY = "auto";
    },
    invisible() {
      this.overflowY = "hidden";
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        //  console.log('服务端推送',e);
        this.wsValue = JSON.parse(e.result);
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    clickRow(row) {
      if (this.selectedRow === row.index) {
        this.selectedRow = undefined;
      } else {
        this.selectedRow = row.index;
      }
    }
  }
};
</script>
<style ang="scss" scoped>
.tabBorder {
  border-style: solid;
  height: 90%;
  position: relative;
}
.tabText {
  position: absolute;
  top: 38%;
  width: 100%;
}
.tabli {
  list-style: none;
  height: 100%;
  padding-left: 1px;
  float: left;
  cursor: default;
}
/*最外层透明*/
/deep/ .el-table,
/deep/ .el-table__expanded-cell {
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

/deep/ .el-pager li {
  background-color: transparent;
}
/deep/ .el-pagination__jump .el-input__inner {
  color: #fff;
  background-color: transparent;
}
/deep/ .el-pagination__sizes .el-input__inner {
  color: #fff;
  background-color: transparent;
}
/deep/ .el-pagination .btn-prev,
.el-pagination .btn-next {
  color: #fff;
  background-color: transparent;
}
/deep/ .btn-next {
  color: #fff;
  background-color: transparent;
}
/deep/ .el-pagination button:disabled {
  background-color: transparent;
}
/deep/.el-pagination {
  color: #fff;
}
/deep/ .el-pagination__jump {
  color: #fff;
}
/deep/.el-pagination .el-pagination__total {
  color: #fff;
}
/deep/ .el-table .cell {
  white-space: pre !important;
}
/deep/.el-pager li.btn-quicknext,
.el-pager li.btn-quickprev {
  line-height: 28px;
  color: #ffffff;
}
::v-deep .el-table::before {
  height: 0px;
}
::v-deep.el-table th{
  border-bottom: none !important;
  border-top: none !important;
}
</style>
